package gui;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JScrollPane;
import javax.swing.JList;

import entities.Person;
import exceptions.IllegalAppointmentException;
import fachlogik.Administration;
import fachlogik.PersonenCellRenderer;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;

import javax.swing.JCheckBox;

public class UserWindow extends JFrame {

private JPanel           contentPane;
private DefaultListModel userModel;
private Person           selectedUser;
private JTextField       tf_user, pf_password;
private CalendarWindow   cw;
private Administration   instance;
private JCheckBox        chkbx_isAdmin;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainWindow mawi = new MainWindow();
                CalendarWindow cawe = new CalendarWindow(mawi);
                UserWindow frame = new UserWindow(cawe);
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public UserWindow(CalendarWindow cw) {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException e) {
    } catch (InstantiationException e) {
    } catch (IllegalAccessException e) {
    } catch (UnsupportedLookAndFeelException e) {
    }
    this.cw = cw;
    this.instance = cw.getInstance();
    setTitle("User Management");
    setDefaultCloseOperation(HIDE_ON_CLOSE);
    setBounds(100, 100, 450, 266);
    setLocationRelativeTo(null);
    setResizable(false);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);
    userModel = new DefaultListModel<>();
    for (Person p : cw.getInstance().getAllUsers())
        userModel.addElement(p);

    JPanel panel = new JPanel();
    contentPane.add(panel, BorderLayout.CENTER);
    panel.setLayout(null);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(12, 10, 162, 207);
    panel.add(scrollPane);

    chkbx_isAdmin = new JCheckBox("is Administrator");
    chkbx_isAdmin.setBounds(195, 69, 206, 23);
    panel.add(chkbx_isAdmin);

    final JList l_user = new JList(userModel);
    l_user.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    l_user.setCellRenderer(new PersonenCellRenderer());
    l_user.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            selectedUser = (Person) l_user.getSelectedValue();
            selectedUserAnzeigen();
        }
    });

    scrollPane.setViewportView(l_user);

    JLabel lblNewLabel = new JLabel("Username:");
    lblNewLabel.setBounds(200, 12, 99, 15);
    panel.add(lblNewLabel);

    JLabel lblNewLabel_1 = new JLabel("Password:");
    lblNewLabel_1.setBounds(200, 47, 104, 15);
    panel.add(lblNewLabel_1);

    tf_user = new JTextField();
    tf_user.setBounds(290, 10, 111, 19);
    panel.add(tf_user);
    tf_user.setColumns(10);

    pf_password = new JTextField();
    pf_password.setBounds(290, 44, 111, 19);
    panel.add(pf_password);

    JButton btn_save = new JButton("save");
    btn_save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (selectedUser != null) {
                selectedUser.setUsername(tf_user.getText());
                selectedUser.setPassword(pf_password.getText());
                selectedUser.setIsAdmin(chkbx_isAdmin.isSelected());
                instance.editPerson(selectedUser);
                refreshList();
            }
        }
    });
    btn_save.setBounds(200, 126, 200, 25);
    panel.add(btn_save);

    JButton btn_saveAsNew = new JButton("save as new User");
    btn_saveAsNew.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!tf_user.getText().equals("")) {
                if (!pf_password.getText().equals("")) {
                    if (!instance.userExists(tf_user.getText())) {
                        Person newUser = new Person();
                        newUser.setUsername(tf_user.getText());
                        newUser.setPassword(pf_password.getText());
                        newUser.setIsAdmin(chkbx_isAdmin.isSelected());
                        instance.addPerson(newUser);
                        refreshList();
                    }
                    else
                        JOptionPane.showMessageDialog(null, "User already exists!", "Error", 0);
                }
                else
                    JOptionPane.showMessageDialog(null, "Please enter a password!", "Error", 0);
            }
            else
                JOptionPane.showMessageDialog(null, "Please enter a username", "Error", 0);
        }
    });
    btn_saveAsNew.setBounds(200, 158, 200, 25);
    panel.add(btn_saveAsNew);

    JButton btn_delete = new JButton("delete");
    btn_delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (selectedUser != null) {
                try {
                    if (instance.getUser().getId() != selectedUser.getId()) {
                        if (selectedUser.getIsAdmin() == true) {
                            ArrayList<Person> admins = new ArrayList<>();
                            for (Person p : instance.getAllUsers()) {
                                if (p.getIsAdmin())
                                    admins.add(p);
                            }

                            if (admins.size() > 1)
                                instance.removePerson(selectedUser);
                            else
                                JOptionPane.showMessageDialog(null, "Can't delete last administrator");
                        }
                        else {
                            instance.removePerson(selectedUser);
                        }
                    }
                    else {
                        JOptionPane.showMessageDialog(null, "Can't delete oneself!");
                    }
                } catch (IllegalAppointmentException e1) {
                    AppointmentDialog AppDia = new AppointmentDialog(e1.getWrongApp(), null);
                    JOptionPane.showMessageDialog(null, "Appointment "
                            + e1.getWrongApp().getName()
                            + "begins after ending!",
                            e1.getWrongApp().getName() + "has caused an error!", 0);
                    e1.printStackTrace();
                }
                refreshList();
            }
        }
    });
    btn_delete.setBounds(200, 190, 200, 25);
    panel.add(btn_delete);

    JButton btnNewButton = new JButton("Clear");
    btnNewButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tf_user.setText("");
            pf_password.setText("");
            selectedUser = null;
            refreshList();
        }
    });
    btnNewButton.setBounds(200, 94, 200, 25);
    panel.add(btnNewButton);

}

public void refreshList() {
    userModel.clear();
    for (Person p : instance.getAllUsers())
        userModel.addElement(p);
}

public void selectedUserAnzeigen() {
    if (selectedUser != null) {
        tf_user.setText(selectedUser.getUsername());
        // System.out.println(selectedUser.getPassword());
        pf_password.setText(selectedUser.getPassword());
        chkbx_isAdmin.setSelected(selectedUser.getIsAdmin());
    }
    else {
        tf_user.setText("");
        pf_password.setText("");
        chkbx_isAdmin.setSelected(false);
    }
}
}
